from odoo import api, fields, models
from odoo.exceptions import AccessDenied
from odoo.http import request


class ResUsers(models.Model):
    _inherit = 'res.users'

    dingtalk_id = fields.Char('钉钉id')
    # dingtalk_openid = fields.Char('钉钉openid')
    dingtalk_unionid = fields.Char('钉钉unionid')

    def _check_credentials(self, password, env):
        """
        用户验证
        """
        try:
            return super(ResUsers, self)._check_credentials(password, env)
        except AccessDenied:
            # 钉钉扫码触发的用户验证方法
            if request.session.dingtalk_auth:
                request.session.dingtalk_auth = None
            else:
                raise AccessDenied

    def current_user(self):
        objs = self.sudo().search([])
        return {obj.dingtalk_id: obj for obj in objs if obj.dingtalk_id}

    def add_user(self, users):
        current_users = self.current_user()
        for u in users:
            userid = str(u['userid'])
            if userid in current_users.keys() or not u['email']: continue
            val = {
                "login": u['email'],
                "name": u['name'],
                "password": u['mobile'],
                'groups_id': self.env.ref('base.group_user'),
                'dingtalk_id': u['userid'],
                'company_ids': [(6, 0, [self.env.company.id])],
                'company_id': self.env.company.id,
                'notification_type': 'inbox',
                'dingtalk_unionid': u['unionid'],
                'lang': 'zh_CN'
            }
            self.env['res.users'].sudo().create(val)

    def update_user(self, users):
        current_users = self.current_user()
        for u in users:
            unionid = u['unionid']
            if unionid not in current_users.keys(): continue
            if u['email'] != current_users[unionid].login:
                current_users[unionid].login = u['email']
            if u['name'] != current_users[unionid].name:
                current_users[unionid].name = u['name']


